import * as Printer from "./printer.js"
import CaseNoIndex from './case-no-index.js';
import CaseWidthIndex from './case-with-index.js';
import CaseWidthIndex2 from './case-with-index-2.js';
import CaseOneByOne from './case-one-after-another.js';
import CaseAllByAll from './case-all-after-all.js';
import CaseCallback from './case-callback.js';
import CaseBP from './case-best-practice.js';

const _CASES_ = Object.freeze({
    'default': CaseNoIndex,
    'withindex': CaseWidthIndex,
    'withindex2': CaseWidthIndex2,
    'noindex': CaseNoIndex,
    'onebyone': CaseOneByOne,
    'callback': CaseCallback,
    'allbyall': CaseAllByAll,
    'BP': CaseBP,
});
const _DEFAULT_VALUES_ = Object.freeze({
    DBCount: 1,
    TableCount: 1,
    RecordCount: 10,
    DataSizeInKBytes: 512,

    CustomReadX: 100,
    CustomReadInterval: 500,//ms
});
Math && (Math.randomInt = (min, max) => { return Math.floor(Math.random() * (max - min)) + min; })
let _caseHandler = undefined;
let _autoH = undefined;
let _body = undefined;

async function TestReadSpeed(count) {
    await _caseHandler.Open();
    const _result = await _caseHandler.RandomReadXData(count);
    Printer.Print(_result);
    Printer.PrintMsg('done');
}

function _GetInputValue(id, defaultValue) {
    const v = _body.querySelector(`#${id}`).value;
    return v === '' ? defaultValue : parseInt(v);
}

function ONClick(id, cb) {
    _body.querySelector(`#${id}`).onclick = evt => {
        cb(evt);
    }
}

const _MAX_TIMES_ = 50;
function _AutoRead() {
    let _times = 0;
    const _count = _GetInputValue('iptX', _DEFAULT_VALUES_.CustomReadX);
    const _ms = _GetInputValue('iptInterval', _DEFAULT_VALUES_.CustomReadInterval);
    _autoH = setInterval(_ => {
        TestReadSpeed(_count);

        ++_times;
        if (_times >= _MAX_TIMES_) {
            _StopAutoRead();
        }
    }, _ms);
    _body.querySelector('#btnAuto').onclick = _StopAutoRead;
    _body.querySelector('#btnAuto').innerText = 'Stop';
}

function _StopAutoRead() {
    _autoH && clearInterval(_autoH);
    _autoH = undefined;
    _body.querySelector('#btnAuto').onclick = _AutoRead;
    _body.querySelector('#btnAuto').innerText = 'Start Auto';
}

function OpenCase(name) {
    if (_caseHandler) {
        _caseHandler.Close();
        _caseHandler = undefined;
    }
    const _tmp = _CASES_[name];
    if (_tmp) {
        _caseHandler = _tmp();
        return true;
    }
    return false;
}

window.onload = _ => {
    _body = document.body;
    _body.querySelector('#ipt1').placeholder = `要创建几个数据库(${_DEFAULT_VALUES_.DBCount})`;
    _body.querySelector('#ipt2').placeholder = `每个数据库几张表(${_DEFAULT_VALUES_.TableCount})`;
    _body.querySelector('#ipt3').placeholder = `每张表几份记录(${_DEFAULT_VALUES_.RecordCount})`;
    _body.querySelector('#ipt5').placeholder = `每份记录多少KiB(${_DEFAULT_VALUES_.DataSizeInKBytes})`;
    _body.querySelector('#iptX').placeholder = `自定义读取数量(${_DEFAULT_VALUES_.CustomReadX})`;
    _body.querySelector('#iptInterval').placeholder = `自定义读取间隔(ms)(${_DEFAULT_VALUES_.CustomReadInterval})`;
    _body.querySelector('#selector').onchange = evt => {
        //console.log(evt);
        //const _idx = evt.target.selectedIndex;
        const _name = evt.target.selectedOptions[0].value;
        if (OpenCase(_name)) {
            Printer.PrintMsg('case switched.');
        }
    }

    ONClick('btnClear', _ => { Printer.Clear(); })
    ONClick('btnCopy', _ => {
        let copyTextarea = document.querySelector('#ta');
        copyTextarea.focus();
        copyTextarea.value = _body.querySelector('#myTable').outerHTML;
        copyTextarea.select();
        try {
            let successful = document.execCommand('copy');
            if (successful) {
                Printer.PrintMsg('copied to clipboard.');
            } else {
                Printer.PrintMsg('copy error.');
            }
        } catch (err) {
            Printer.PrintMsg('copy error2.');
        }
    })
    ONClick('btn1', _ => { TestReadSpeed(1); })
    ONClick('btn2', _ => { TestReadSpeed(10); })
    ONClick('btn3', _ => { TestReadSpeed(100); })
    ONClick('btn4', _ => { TestReadSpeed(1000); })
    ONClick('btnX', _ => { TestReadSpeed(_GetInputValue('iptX'), _DEFAULT_VALUES_.CustomReadX); })

    ONClick('btnCreate', _ => {
        const _dbs = _GetInputValue('ipt1', _DEFAULT_VALUES_.DBCount);
        const _tbls = _GetInputValue('ipt2', _DEFAULT_VALUES_.TableCount);
        const _records = _GetInputValue('ipt3', _DEFAULT_VALUES_.RecordCount);
        const _dataSizeInBytes = _GetInputValue('ipt5', _DEFAULT_VALUES_.DataSizeInKBytes) * 1024;
        _caseHandler.CreateXDBYTableZData(_dbs, _tbls, _records, _dataSizeInBytes);
    });
    ONClick('btnDelete', _ => {
        _caseHandler.DeleteAllDB();
        Printer.PrintMsg('all deleted.');
    })


    ONClick('btnAuto2', _ => {
        const _data = _GetInputValue('iptA', 50);
        const _cap = _GetInputValue('iptB', 10);
        TestReadSpeed_maxCapacity(_data, _cap);
    })

    _StopAutoRead();
    Printer.PrintHead();
    OpenCase('default');
}
